package com.jwong.test;

import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.dsl.ExecWatch;
import io.fabric8.kubernetes.client.utils.InputStreamPumper;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecPipesExample {

    public static void main(String[] args) {
        Config config = new ConfigBuilder().withMasterUrl("https://localhost:8443/").build();
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        try (
                KubernetesClient client = new DefaultKubernetesClient(config);
                ExecWatch watch = client.pods().withName("curl")
                        .redirectingInput()
                        .redirectingOutput()
                        .redirectingError()
                        .redirectingErrorChannel()
                        .exec();)
        {
            InputStreamPumper.pump(watch.getOutput(), (b, o, l) -> System.out.print(new String(b, o, l)),
                    executorService);
            watch.getInput().write("ls -al\n".getBytes());
            Thread.sleep(10 * 1000L);
        } catch (Exception e) {
            throw KubernetesClientException.launderThrowable(e);
        } finally {
            executorService.shutdownNow();
        }
    }
}
